package com.bestcem.xm.user.grpc.service;

import com.bestcem.bp.grpc.v1.base.Page;
import com.bestcem.bp.xm.user.grpc.v1.enums.OrgSourceEnum;
import com.bestcem.bp.xm.user.grpc.v1.enums.PackageEditionEnum;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.DateUtil;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.common.core.uitls.GrpcDateUtil;
import com.bestcem.xm.user.grpc.client.PackageGrpcService;
import com.bestcem.xm.user.grpc.client.dto.PackageDTO;
import com.bestcem.xm.user.grpc.service.converter.OrgConditionConvert;
import com.bestcem.xm.user.grpc.service.converter.OrganizationConvert;
import com.bestcem.xm.user.grpc.service.param.ListOrgByPageParam;
import com.bestcem.xm.user.grpc.service.param.ListOrgsByFilterParam;
import com.bestcem.xm.user.grpc.service.param.ListOrgsByPagingParam;
import com.bestcem.xm.user.grpc.service.param.PageParam;
import com.bestcem.xm.user.service.OrganizationService;
import com.bestcem.xm.user.service.UserOrgBusinessService;
import com.bestcem.xm.user.service.dto.PageResponseDTO;
import com.bestcem.xm.user.service.dto.user.OrgConditionDTO;
import com.bestcem.xm.user.service.dto.user.OrganizationDTO;
import com.bestcem.xm.user.util.business.UserUtil;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 公司信息相关服务
 *
 * @author jishuo.yan <jishuo.yan@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/8 16:00
 */
@Slf4j
@GrpcService
public class OrganizationGrpcService extends OrgServiceGrpc.OrgServiceImplBase {

    @Resource
    private OrganizationService organizationService;

    @Resource
    private UserOrgBusinessService userOrgBusinessService;

    @Resource
    private PackageGrpcService packageGrpcService;

    @Resource
    private UserUtil userUtil;

    /**
     * 根据orgId或者orgCode获取公司信息
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @Author yun.pan <yun.pan@idiaoyan.com>
     * @date 2022/03/08 15:30
     */
    @Override
    public void getOrgByIdOrCode(GetOrgByIdOrCodeRequest request, StreamObserver<GetOrgByIdOrCodeResponse> responseObserver) {
        GetOrgByIdOrCodeResponse.Builder builder = GetOrgByIdOrCodeResponse.newBuilder();
        // 获取用户Id
        String orgId = request.getId();
        String orgCode = request.getCode();
        ServiceResult<OrganizationDTO> serviceResult;
        if (StringUtils.isNotBlank(orgId)) {
            serviceResult = organizationService.selectByPrimaryKey(orgId);
        } else {
            serviceResult = organizationService.selectByOrgCode(orgCode);
        }
        if (serviceResult.isSuccess() && Objects.nonNull(serviceResult.getData())) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.setOrg(OrganizationConvert.organizationDtoToOrganization(serviceResult.getData()));
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error("未查询到相关org信息"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据搜索条件查询公司列表
     *
     * @param request          请求参数消息
     * @param responseObserver 返回值观察者
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:23 2022/6/28
     */
    @Override
    public void listOrgs(ListOrgsRequest request, StreamObserver<ListOrgsResponse> responseObserver) {
        ListOrgsResponse.Builder builder = ListOrgsResponse.newBuilder();

        // 获取并转换参数
        OrgCondition org = request.getOrg();
        OrgConditionDTO orgConditionDTO = OrgConditionConvert.msg2Dto(org);
        String search = request.getSearch();
        List<String> fields = request.getFieldsList();
        List<Integer> statuses = request.getStatusesValueList();

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(orgConditionDTO);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 根据搜索条件查询公司列表
        ServiceResult<List<OrganizationDTO>> result = organizationService.listOrganizations(orgConditionDTO, statuses, search, fields, null);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        List<Organization> organizations = result.getData().stream().map(OrganizationConvert::dto2Msg).collect(Collectors.toList());
        builder.addAllOrgs(organizations);
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据公司基础参数查询一个公司信息
     *
     * @param request          请求参数消息
     * @param responseObserver 返回值观察者
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 14:12 2022/7/1
     */
    @Override
    public void getOrg(GetOrgRequest request, StreamObserver<GetOrgResponse> responseObserver) {
        GetOrgResponse.Builder builder = GetOrgResponse.newBuilder();

        // 获取并转换参数
        OrgCondition org = request.getOrg();
        OrgConditionDTO orgConditionDTO = OrgConditionConvert.msg2Dto(org);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(orgConditionDTO);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        // 根据搜索条件查询公司列表
        ServiceResult<List<OrganizationDTO>> result = organizationService.listOrganizations(orgConditionDTO, 1);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        List<Organization> organizations = result.getData().stream().map(OrganizationConvert::dto2Msg).collect(Collectors.toList());
        Organization organization;
        if (!CollectionUtils.isEmpty(organizations)) {
            organization = organizations.get(0);
            builder.setOrg(organization);
        }
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 更新公司信息
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * qiongyu <qiongyu.cui@idiaoyan.com>
     * @date 2022/03/08 16:22
     */
    @Override
    public void updateOrg(UpdateOrgRequest request, StreamObserver<UpdateOrgResponse> responseObserver) {
        UpdateOrgResponse.Builder builder = UpdateOrgResponse.newBuilder();
        String orgId = request.getId();
        OrganizationDTO dto = OrganizationConvert.operateOrgToOrganizationDTO(request.getOrg());
        if (request.hasBackend()) {
            dto.setBackend(request.getBackend());
        }
        dto.setOrgId(orgId);
        ServiceResult<String> serviceResult = organizationService.updateOrg(dto);
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 检验组织code格式是否正确
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @date 2022/03/15 15:00
     */
    @Override
    public void checkOrgCode(CheckOrgCodeRequest request, StreamObserver<CheckOrgCodeResponse> responseObserver) {
        CheckOrgCodeResponse.Builder builder = CheckOrgCodeResponse.newBuilder();
        //获取用户Id
        String code = request.getCode();
        ServiceResult<String> serviceResult = userOrgBusinessService.checkOrgCode(code);
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(true);
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.success());
            builder.setValid(false);

        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 创建公司并设置密码
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * qiongyu.cui <qiongyu.cui@idiaoyan.com>
     * @date 2022/03/15 15:00
     */
    @Override
    public void createOrgWithPwd(CreateOrgWithPwdRequest request, StreamObserver<CreateOrgWithPwdResponse> responseObserver) {
        CreateOrgWithPwdResponse.Builder builder = CreateOrgWithPwdResponse.newBuilder();
        // 获取用户Id
        OrganizationDTO dto = OrganizationConvert.operateOrgToOrganizationDTO(request.getOrg());
        String password = request.getPassword();

        Integer source = OrgSourceEnum.OrgSource.OPEN_PLATFORM_VALUE;
        if (request.hasSource()) {
            source = request.getSourceValue();
        }
        String sourceRemark = request.getSourceRemark();
        String orgParentCode = request.getOrgParentCode();
        ServiceResult<String> serviceResult = userOrgBusinessService.createOrganization(dto, password, source,
                sourceRemark, false, orgParentCode);
        if (serviceResult.isSuccess()) {
            // 创建成功
            builder.setStatus(RpcStatusResult.success());
            builder.setId(serviceResult.getData());
        } else {
            // 创建失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 检验公司code是否存在
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.cn>
     * @date 2022/03/15 15:16
     */
    @Override
    public void checkOrgCodeExist(CheckOrgCodeExistRequest request, StreamObserver<CheckOrgCodeExistResponse> responseObserver) {
        CheckOrgCodeExistResponse.Builder builder = CheckOrgCodeExistResponse.newBuilder();
        // 获取用户Id
        String code = request.getCode();
        ServiceResult<String> serviceResult = userOrgBusinessService.checkOrgCode(code);
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            OrganizationDTO organizationDTO = organizationService.selectByOrgCode(code).getData();
            builder.setExist(organizationDTO != null);
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 获取公司的版本信息
     *
     * @param request 请求信息
     * @return responseObserver 返回结果
     * @author yanjishuo <jishuo.yan@idiaoyan.com>
     * @author yun.pan <yun.pan@idiaoyan.com>
     * @date 2022/03/08 15:30
     */
    @Override
    public void getOrgPackageEdition(GetOrgPackageEditionRequest request, StreamObserver<GetOrgPackageEditionResponse> responseObserver) {
        GetOrgPackageEditionResponse.Builder builder = GetOrgPackageEditionResponse.newBuilder();
        // 获取用户Id
        String orgId = request.getId();
        ServiceResult<OrganizationDTO> serviceResult = organizationService.selectByPrimaryKey(orgId);
        if (Objects.nonNull(serviceResult.getData())) {
            String packageId = serviceResult.getData().getPackageId();
            // 获取套餐信息
            PackageDTO packageDTO = packageGrpcService.getById(packageId);
            if (Objects.nonNull(packageDTO)) {
                // 获取版本信息
                Integer edition = packageDTO.getEdition();
                if (Objects.nonNull(edition)) {
                    // 查询成功
                    builder.setStatus(RpcStatusResult.success());
                    builder.setPackageEdition(PackageEditionEnum.PackageEdition.forNumber(edition));
                }
            } else {
                builder.setStatus(RpcStatusResult.error("获取套餐失败 id:" + packageId));
            }
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 创建公司信息
     *
     * @param request          请求信息
     * @param responseObserver 返回结果
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/11 21:03
     */
    @Override
    public void createOrg(CreateOrgRequest request, StreamObserver<CreateOrgResponse> responseObserver) {
        CreateOrgResponse.Builder builder = CreateOrgResponse.newBuilder();

        // 参数转换
        OrganizationDTO dto = OrganizationConvert.createOrgToOrganizationDTO(request.getOrg());
        // 新增公司信息
        ServiceResult<String> createResult = userOrgBusinessService.createOrganization(dto, "", dto.getSource(),
                dto.getSourceRemark(), false, "");
        if (createResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setId(createResult.getData());
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(createResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过预约，创建公司
     *
     * @param request          请求信息
     * @param responseObserver 返回结果
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/06/30 11:12
     */
    @Override
    public void acceptBooking(AcceptBookingRequest request, StreamObserver<AcceptBookingResponse> responseObserver) {
        AcceptBookingResponse.Builder builder = AcceptBookingResponse.newBuilder();

        // 参数转换
        OrganizationDTO dto = OrganizationConvert.createRequestToOrganizationDTO(request);

        // 新增公司信息
        ServiceResult<String> createResult = userOrgBusinessService.acceptBooking(dto, request.getManagerEmail(), request.getManagerPhone());
        if (createResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setOrgId(createResult.getData());
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(createResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 租户管理分页获得公司信息
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/16 16:56
     */
    @Override
    public void listOrgsByPage(ListOrgsByPageRequest request, StreamObserver<ListOrgsByPageResponse> responseObserver) {
        ListOrgsByPageResponse.Builder builder = ListOrgsByPageResponse.newBuilder();

        OrganizationDTO dto = OrganizationConvert.orgCondition2OrganizationDTO(request.getOrg());
        PageParam pageParam = new PageParam(request.getPage().getPage(), request.getPage().getSize());
        ListOrgByPageParam param = new ListOrgByPageParam();
        param.setOrganizationDTO(dto);
        param.setPageParam(pageParam);
        param.setSearch(request.getSearch());
        param.setStartTime(DateUtil.convertDteToString(GrpcDateUtil.getDate(request.getStartTime()), DateUtil.NORM_DATETIME_PATTERN));
        param.setEndTime(DateUtil.convertDteToString(GrpcDateUtil.getDate(request.getEndTime()), DateUtil.NORM_DATETIME_PATTERN));
        if (request.hasFilter()) {
            param.setTimeFilter(request.getFilterValue());
        }
        param.setOrgIdList(request.getOrgIdsList());
        param.setIndustryIdList(request.getIndustryIdsList());
        param.setStatuses(request.getStatusesValueList());

        ServiceResult<PageResponseDTO<OrganizationDTO>> serviceResult = organizationService.listOrganizationsByPage(param);
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.setTotal(Math.toIntExact(serviceResult.getData().getTotal()));
            builder.addAllOrgs(OrganizationConvert.organizationDtosToOrganizations(serviceResult.getData().getRows()));
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 根据package_ids查询租户ids
     *
     * @param request          请求信息
     * @param responseObserver 返回结果
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/5/17 15:12
     */
    @Override
    public void listOrgIdsByPackageIds(ListOrgIdsByPackageIdsRequest request, StreamObserver<ListOrgIdsByPackageIdsResponse> responseObserver) {
        ListOrgIdsByPackageIdsResponse.Builder builder = ListOrgIdsByPackageIdsResponse.newBuilder();

        List<String> packageIdsList = request.getPackageIdsList();
        if (CollectionUtils.isEmpty(packageIdsList)) {
            builder.setStatus(RpcStatusResult.success());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<List<String>> result = organizationService.selectOrgIdsByPackageIds(packageIdsList);
        builder.setStatus(RpcStatusResult.success());
        builder.addAllIds(result.getData());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 获取行业示例的租户代号
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/6/29 15:43
     */
    @Override
    public void listIndustrySampleCodes(ListIndustrySampleCodesRequest request, StreamObserver<ListIndustrySampleCodesResponse> responseObserver) {
        // 设置返回值
        ListIndustrySampleCodesResponse.Builder builder = ListIndustrySampleCodesResponse.newBuilder();
        // 查询对应的公司信息
        ServiceResult<List<OrganizationDTO>> serviceResult = userOrgBusinessService.listIndustrySampleCodes(request.getCodesList());
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            if (CollectionUtils.isNotEmpty(serviceResult.getData())) {
                builder.addAllCodes(OrganizationConvert.orgDtos2SampleCodes(serviceResult.getData()));
            }
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 根据筛选条件筛选公司信息
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/07/05 16:14
     */
    @Override
    public void listOrgsByFilter(ListOrgsByFilterRequest request, StreamObserver<ListOrgsByFilterResponse> responseObserver) {

        // 设置返回值
        ListOrgsByFilterResponse.Builder builder = ListOrgsByFilterResponse.newBuilder();
        ListOrgsByFilterParam param = OrganizationConvert.listOrgsByFilterRequest2Param(request);
        ServiceResult<PageResponseDTO<OrganizationDTO>> serviceResult = organizationService.listOrgsByFilter(param);
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.setTotal(Math.toIntExact(serviceResult.getData().getTotal()));
            builder.addAllOrgs(OrganizationConvert.organizationDtosToOrganizations(serviceResult.getData().getRows()));
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 通过公司id校验公司是否到期
     *
     * @param request
     * @param responseObserver
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/7/5 17:27
     */
    @Override
    public void checkOrgExpire(CheckOrgExpireRequest request, StreamObserver<CheckOrgExpireResponse> responseObserver) {
        // 设置返回值
        CheckOrgExpireResponse.Builder builder = CheckOrgExpireResponse.newBuilder();
        // 查询对应的公司信息
        ServiceResult<Boolean> serviceResult = userOrgBusinessService.checkOrgExpire(request.getId());
        if (serviceResult.isSuccess()) {
            // 查询成功
            builder.setStatus(RpcStatusResult.success());
            builder.setExpired(!serviceResult.getData());
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void createOrgFromBackend(CreateOrgFromBackendRequest request,
                                     StreamObserver<CreateOrgFromBackendResponse> responseObserver) {
        CreateOrgFromBackendResponse.Builder builder = CreateOrgFromBackendResponse.newBuilder();

        // 参数转换
        OrganizationDTO dto = OrganizationConvert.createRequestToOrganizationDTO(request);

        // 新增公司信息
        ServiceResult<String> createResult = userOrgBusinessService.createOrgFromBackend(dto, request.getManagerEmail(), request.getManagerPhone());
        if (createResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setId(createResult.getData());
        } else {
            // 查询失败
            builder.setStatus(RpcStatusResult.error(createResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


//    @Override
//    public void listOrgsFieldByPage(ListOrgsfieldByPageRequest request, StreamObserver<ListOrgsfieldByPageResponse> responseObserver) {
//        ListOrgsfieldByPageResponse.Builder builder = ListOrgsfieldByPageResponse.newBuilder();
//
//        // 获取并转换参数
//        OrgCondition org = request.getOrg();
//        OrgConditionDTO orgConditionDTO = OrgConditionConvert.msg2Dto(org);
//        // 分页
//        Page page = request.getPage();
//
//        ListOrgsByPagingParam param = new ListOrgsByPagingParam();
//        param.setSearch(request.getSearch());
//        param.setFields(request.getFieldsList());
//        param.setStatuses(request.getStatusesValueList());
//        param.setSources(request.getSourcesValueList());
//        param.setSourceRemarks(request.getSourceRemarksList());
//        param.setOrgIds(request.getOrgIdsList());
//        param.setIndustryIds(request.getIndustryIdsList());
//        if (request.hasFilter()){
//            param.setTimeFilter(request.getFilterValue());
//            param.setStartTime(GrpcDateUtil.getDate(request.getStartTime()));
//            param.setEndTime(GrpcDateUtil.getDate(request.getEndTime()));
//        }
//
//
//        // 参数校验
//        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(orgConditionDTO);
//        if (!CollectionUtils.isEmpty(violations)) {
//            ConstraintViolation<Object> violation = violations.iterator().next();
//            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
//            responseObserver.onNext(builder.build());
//            responseObserver.onCompleted();
//            return;
//        }
//        // 根据搜索条件查询公司列表
//        ServiceResult<PageResponseDTO<OrganizationDTO>> result = organizationService.listOrgsByPaging(orgConditionDTO, param, page);
//        if (!result.isSuccess()) {
//            builder.setStatus(RpcStatusResult.error(result.getMsg()));
//            responseObserver.onNext(builder.build());
//            responseObserver.onCompleted();
//            return;
//        }
//        PageResponseDTO<OrganizationDTO> data = result.getData();
//        List<Organization> organizations = data.getRows().stream().map(OrganizationConvert::dto2Msg).collect(Collectors.toList());
//        builder.addAllOrgs(organizations);
//        builder.setTotal(data.getTotal().intValue());
//        builder.setStatus(RpcStatusResult.success());
//        responseObserver.onNext(builder.build());
//        responseObserver.onCompleted();
//    }


    @Override
    public void listOrgsFieldByPage(ListOrgsFieldByPageRequest request, StreamObserver<ListOrgsFieldByPageResponse> responseObserver) {
        ListOrgsFieldByPageResponse.Builder builder = ListOrgsFieldByPageResponse.newBuilder();

        // 获取并转换参数
        OrgCondition org = request.getOrg();
        OrgConditionDTO orgConditionDTO = OrgConditionConvert.msg2Dto(org);
        // 分页
        Page page = request.getPage();

        ListOrgsByPagingParam param = new ListOrgsByPagingParam();
        param.setSearch(request.getSearch());
        param.setFields(request.getFieldsList());
        param.setStatuses(request.getStatusesValueList());
        param.setSources(request.getSourcesValueList());
        param.setSourceRemarks(request.getSourceRemarksList());
        param.setOrgIds(request.getOrgIdsList());
        param.setIndustryIds(request.getIndustryIdsList());
        if (request.hasFilter()) {
            param.setTimeFilter(request.getFilterValue());
            param.setStartTime(GrpcDateUtil.getDate(request.getStartTime()));
            param.setEndTime(GrpcDateUtil.getDate(request.getEndTime()));
        }


        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(orgConditionDTO);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            builder.setStatus(RpcStatusResult.error(violation.getMessage()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        // 根据搜索条件查询公司列表
        ServiceResult<PageResponseDTO<OrganizationDTO>> result = organizationService.listOrgsByPaging(orgConditionDTO, param, page);
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        PageResponseDTO<OrganizationDTO> data = result.getData();
        List<Organization> organizations = data.getRows().stream().map(OrganizationConvert::dto2Msg).collect(Collectors.toList());
        builder.addAllOrgs(organizations);
        builder.setTotal(data.getTotal().intValue());
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    @Override
    public void getCorpUrlByCode(GetCorpUrlByCodeRequest request, StreamObserver<GetCorpUrlByCodeResponse> responseObserver) {
        GetCorpUrlByCodeResponse.Builder builder = GetCorpUrlByCodeResponse.newBuilder();
        String corpUrl = userUtil.getCorpUrl(request.getOrgCode());

        if (StringUtils.isNotBlank(corpUrl)) {
            //查询成功
            builder.setCorpUrl(corpUrl);
            builder.setStatus(RpcStatusResult.success());
        } else {
            //查询失败
            builder.setStatus(RpcStatusResult.error("getCorpUrlByCode查询失败"));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
